{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "import os\n",
    "import jieba\n",
    "import torch\n",
    "import pickle\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "import pandas as pd\n",
    "\n",
    "from ark_nlp.model.tm.bert import Bert\n",
    "from ark_nlp.model.tm.bert import BertConfig\n",
    "from ark_nlp.model.tm.bert import Dataset\n",
    "from ark_nlp.model.tm.bert import Task\n",
    "from ark_nlp.model.tm.bert import get_default_model_optimizer\n",
    "from ark_nlp.model.tm.bert import Tokenizer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 一、数据读入与处理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. 数据读入"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data_df = pd.read_json('../data/source_datasets/CHIP-STS/CHIP-STS_train.json')\n",
    "train_data_df = (train_data_df\n",
    "                 .rename(columns={'text1': 'text_a', 'text2': 'text_b', 'category': 'condition'})\n",
    "                 .loc[:,['text_a', 'text_b', 'condition', 'label']])\n",
    "\n",
    "dev_data_df = pd.read_json('../data/source_datasets/CHIP-STS/CHIP-STS_dev.json')\n",
    "dev_data_df = dev_data_df[dev_data_df['label'] != \"NA\"]\n",
    "dev_data_df = (dev_data_df\n",
    "                 .rename(columns={'text1': 'text_a', 'text2': 'text_b', 'category': 'condition'})\n",
    "                 .loc[:,['text_a', 'text_b', 'condition', 'label']])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tm_train_dataset = Dataset(train_data_df)\n",
    "tm_dev_dataset = Dataset(dev_data_df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. 词典创建和生成分词器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = Tokenizer(vocab='bert-base-chinese', max_seq_len=64)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. ID化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tm_train_dataset.convert_to_ids(tokenizer)\n",
    "tm_dev_dataset.convert_to_ids(tokenizer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<br>\n",
    "\n",
    "### 二、模型构建"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. 模型参数设置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config = BertConfig.from_pretrained('bert-base-chinese',\n",
    "                                    num_labels=len(tm_train_dataset.cat2id))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. 模型创建"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.cuda.empty_cache()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dl_module = Bert.from_pretrained('bert-base-chinese', \n",
    "                                 config=config)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<br>\n",
    "\n",
    "### 三、任务构建"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. 任务参数和必要部件设定"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 设置运行次数\n",
    "num_epoches = 5\n",
    "batch_size = 32"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "optimizer = get_default_model_optimizer(dl_module)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. 任务创建"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = Task(dl_module, optimizer, 'ce', cuda_device=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. 训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.fit(tm_train_dataset, \n",
    "          tm_dev_dataset,\n",
    "          lr=2e-5,\n",
    "          epochs=num_epoches, \n",
    "          batch_size=batch_size\n",
    "         )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<br>\n",
    "\n",
    "### 四、CBLUE提交生成"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ark_nlp.model.tm.bert import Predictor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tm_predictor_instance = Predictor(model.module, tokenizer, tm_train_dataset.cat2id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "from tqdm import tqdm\n",
    "\n",
    "test_df = pd.read_json('../data/source_datasets/CHIP-STS/CHIP-STS_test.json')\n",
    "\n",
    "submit = []\n",
    "for _id, _text_a, _text_b, _condition in tqdm(zip(\n",
    "    test_df['id'],\n",
    "    test_df['text1'],\n",
    "    test_df['text2'],\n",
    "    test_df['category']\n",
    ")):\n",
    "    if _condition == 'daibetes':\n",
    "        _condition = 'diabetes'\n",
    "\n",
    "    predict_ = tm_predictor_instance.predict_one_sample([_text_a, _text_b])[0]\n",
    "    \n",
    "    submit.append({\n",
    "        'id': str(_id),\n",
    "        'text1': _text_a,\n",
    "        'text2': _text_b,\n",
    "        'label': predict_,\n",
    "        'category': _condition\n",
    "    })"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "output_path = '../data/output_datasets/CHIP-STS_test.json'\n",
    "\n",
    "with open(output_path, 'w', encoding='utf-8') as f:\n",
    "    f.write(json.dumps(submit, ensure_ascii=False))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
